package com.example.authserver.filter;

import com.wf.captcha.utils.CaptchaUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class ValidateCodeFilter extends OncePerRequestFilter {
    @Autowired
    private AuthenticationFailureHandler authenticationFailureHandler;

//    private static final String APPID="30c3b1a1a797262538846416fdc36e95";
//    private static final String APPSECRET="2d8760dd90917b2d37d069eb3880d76c";

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        if(httpServletRequest.getRequestURI().equals("/login")){
            try {
                validate(new ServletWebRequest(httpServletRequest));
            }catch (BadCredentialsException e){
                authenticationFailureHandler.onAuthenticationFailure(httpServletRequest, httpServletResponse, e);
                return;
            }catch (Exception e){
                e.printStackTrace();
                return;
            }
        }
        filterChain.doFilter(httpServletRequest,httpServletResponse);
    }

    private void validate(ServletWebRequest request) throws Exception {
        String vercode = ServletRequestUtils.getStringParameter(request.getRequest(), "vercode");
        if (!CaptchaUtil.ver(vercode,request.getRequest())) {
            throw new BadCredentialsException("验证码错误！");
        }
    }
}
